#include <iostream>
#include <cstring>
#include <vector>
#include <libpq-fe.h>
using namespace std;
void print_table(PGconn *conn,string table_name){
    string sql="SELECT * FROM "+table_name;
    PGresult *res=PQexec(conn,sql.c_str());
    if(PQresultStatus(res)!=PGRES_TUPLES_OK){
        cerr<<"Query failed:"<<PQerrorMessage(conn)<<endl;
        PQclear(res);
        return;
    }
    const int num_fields = PQnfields(res);
    const int num_rows = PQntuples(res);
    vector<int> col_widths(num_fields);
    for(int i=0;i<num_fields;++i) {
        col_widths[i]=static_cast<int>(strlen(PQfname(res,i)));
        for(int j=0;j<num_rows;++j) {
            const char* value=PQgetvalue(res,j,i);
            if(value) col_widths[i]=max(col_widths[i],static_cast<int>(strlen(value)));
        }
    }
    cout<<"Table:"<<table_name<<"\n|";
    for(int i=0;i<num_fields;++i)
        cout<<string(col_widths[i],'-')<<(i<num_fields-1?"-+-":"-|");
    cout<<"\n|";
    for(int i=0;i<num_fields;++i) {
        cout.width(col_widths[i]);
        cout<<left<<PQfname(res,i)<<" | ";
    }
    cout<<"\n|";
    for(int i=0;i<num_fields;++i)
        cout<<string(col_widths[i],'-')<<(i<num_fields-1?"-+-":"-|");
    cout<<'\n';
    for(int row=0;row<num_rows;++row) {
        cout<<'|';
        for(int col=0;col<num_fields;++col) {
            const char* value=PQgetvalue(res,row,col);
            cout.width(col_widths[col]);
            cout<<left<<(value?value:"NULL")<<" | ";
        }
        cout<<"\n|";
        for(int i=0;i<num_fields;++i)
            cout<<string(col_widths[i],'-')<<(i<num_fields-1?"-+-":"-|");
        cout<<'\n';
    }
    if(num_rows==0) cout<<"No data in table.\n";
    cout<<"Table end.\n";
    PQclear(res);
}
int main(){
    PGconn *conn=PQconnectdb("host=localhost port=5432 dbname=user user=postgres password=123456");
    if(PQstatus(conn)!=CONNECTION_OK){
        cerr<<"Connection failed:"<<PQerrorMessage(conn)<<endl;
        PQfinish(conn);
        return -1;
    }
    print_table(conn,"users");
    print_table(conn,"files");
    PQfinish(conn);
    return 0;
}